﻿using System.Web;
using EPiServer;
using EPiServer.Core;


namespace EPiServer.Templates.RelatePlus.Templates.PageEntity.TagBox
{
    public class TagEventHandler : System.Web.IHttpModule
    {
        private static bool isInitialized = false;

        #region IHttpModule Members

        public void Dispose()
        {
        }

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            lock (this)
            {
                if (!isInitialized)
                {
                    DataFactory.Instance.DeletingPage += new PageEventHandler(DeletingPage);
                    isInitialized = true;
                }
            }
        }

        #endregion

        /// <summary>
        /// Deletings the page.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EPiServer.PageEventArgs"/> instance containing the event data.</param>
        void DeletingPage(object sender, PageEventArgs e)
        {
            if (!PageReference.IsNullOrEmpty(e.PageLink))
            {
                // If e.PageLink points to the wastebasket it means that the "empty recycle bin"-action is being run.
                // If so is the case we need to iterate over the contents of the wastebasket ourselves.
                if (DataFactory.Instance.IsWastebasket(e.PageLink))
                {
                    PageDataCollection pagesInWasteBasket = DataFactory.Instance.GetChildren(e.PageLink);

                    foreach (PageData page in pagesInWasteBasket)
                    {
                        DeletePageEntityByPageData(page);
                    }
                }
                    // A single page is removed from the wastebasket
                else
                {
                    DeletePageEntityByPageData(DataFactory.Instance.GetPage(e.PageLink));
                }
            }
        }

        /// <summary>
        /// Deletes the page entity by page data.
        /// </summary>
        /// <param name="pageBeingDeleted">The page being deleted.</param>
        private void DeletePageEntityByPageData(PageData pageBeingDeleted)
        {
            PageEntity entityToDelete = PageEntityHandler.GetPageEntityByGUID(pageBeingDeleted.PageGuid);

            if (entityToDelete != null)
            {
                PageEntityHandler.RemovePageEntity(entityToDelete);
            }
        }
    }
}